package service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;

import security.MySecurityContextHandle;
import service.interf.IUserBind;

import common.impl.exception.ServiceException;

import dao.interf.IIfwAgentRegInfoDAO;
import dao.interf.IUserBindDAO;
import dao.pojo.IfwAgentRegInfo;
import dao.pojo.UserBind;

public class UserBindImpl extends BaseDataServiceImpl implements IUserBind {

	private IUserBindDAO userBindDao;
	private IIfwAgentRegInfoDAO agentRegInfoDao;

	public void setUserBindDao(IUserBindDAO userBindDao) {
		this.userBindDao = userBindDao;
	}

	public void setAgentRegInfoDao(IIfwAgentRegInfoDAO agentRegInfoDao) {
		this.agentRegInfoDao = agentRegInfoDao;
	}

	public String bindYes(UserBind model) throws Exception {
		// 验证
		String userName = MySecurityContextHandle.getUserName();
		if(!"admin".equals(userName))
			throw new ServiceException("请先登录");
		// 验证主代理
		String masterUser = model.getMasterUser();
		if (StringUtils.isEmpty(masterUser))
			throw new ServiceException("主代理用户名不能为空");
		masterUser = masterUser.replaceAll(" ", "");
		if (masterUser.contains(",") || masterUser.contains("，"))
			throw new ServiceException("绑定失败，主代理只能关联一个");
		if ("admin".equals(masterUser))
			throw new ServiceException("主代理用户名不能为admin");
		List<IfwAgentRegInfo> agentRegInfoL = agentRegInfoDao.findByProperties(
				new String[] { "agentName" }, new Object[] { masterUser });
		if (null == agentRegInfoL || agentRegInfoL.isEmpty())
			throw new ServiceException("绑定失败，主代理不存在");
		// 验证从代理
		String slaveUser = model.getSlaveUser();
		if (StringUtils.isEmpty(slaveUser))
			throw new ServiceException("从代理用户名不能为空");
		slaveUser = slaveUser.replaceAll(" ", "");
		slaveUser = slaveUser.replaceAll("，", ",");
		String[] us = slaveUser.split(",");
		if (slaveUser.startsWith(",") || slaveUser.endsWith(","))
			throw new ServiceException("从代理用户名格式错误");
		String errors = "";
		List<String> userL = new ArrayList<String>();
		for (String u : us) {
			if ("admin".equals(u))
				throw new ServiceException("从代理用户名不能包含admin");
			// 验证从代理用户名和主代理用户名是否相同
			if (u.equals(masterUser))
				throw new ServiceException("从代理用户名不能包含主代理用户名");
			// 验证从代理用户名是否重复
			if (userL.contains(u))
				throw new ServiceException("从代理用户名“" + u + "”重复");
			userL.add(u);
			// 验证代理商是否存在
			agentRegInfoL = agentRegInfoDao.findByProperties(
					new String[] { "agentName" }, new Object[] { u });
			if (null == agentRegInfoL || agentRegInfoL.isEmpty()) {
				errors += "从代理“" + u + "”不存在\n";
				continue;
			}
			// 验证代理商是否已绑定到其他代理商下
			List<UserBind> ubL = userBindDao.findByPropertiesRule("*",
					new String[] { "slaveUser", "slaveUser", "slaveUser",
							"slaveUser" }, new Object[] { u, u + ",%",
							"%," + u + ",%", "%," + u }, new String[] { "or",
							"or", "or", "or" }, new String[] { "=", "like",
							"like", "like" }, "", 0, 0);
			if (null != ubL && !ubL.isEmpty()) {
				String mu_old = ubL.get(0).getMasterUser();
				if (!masterUser.equals(mu_old))
					errors += "“" + u + "”用户已被关联到了“" + mu_old + "”\n";
			}
		}
		if (!StringUtils.isEmpty(errors))
			throw new ServiceException(errors);
		// 绑定
		UserBind userBind = userBindDao.findById(masterUser);
		if (null == userBind) {
			userBind = new UserBind();
			userBind.setMasterUser(masterUser);
			userBind.setSlaveUser(slaveUser);
			userBind.setNote(model.getNote());
			userBindDao.save(userBind);
		} else {
			String su_old = userBind.getSlaveUser();
			if (!StringUtils.isEmpty(su_old)) {
				String[] sus = su_old.split(",");
				List<String> suL = new ArrayList<String>();
				for (String u : sus) {
					suL.add(u);
				}
				for (String u : userL) {
					if (suL.contains(u))
						continue;
					su_old += "," + u;
				}
			} else {
				su_old = slaveUser;
			}
			userBind.setSlaveUser(su_old);
			String note = model.getNote();
			if (!StringUtils.isEmpty(note))
				userBind.setNote(note);
			userBindDao.update(userBind);
		}
		return "1";
	}

	public String bindNo(UserBind model) throws Exception {
		// 验证
		String userName = MySecurityContextHandle.getUserName();
		if(!"admin".equals(userName))
			throw new ServiceException("请先登录");
		// 验证主代理
		String masterUser = model.getMasterUser();
		if (StringUtils.isEmpty(masterUser))
			throw new ServiceException("主代理用户名不能为空");
		masterUser = masterUser.replaceAll(" ", "");
		if (masterUser.contains(",") || masterUser.contains("，"))
			throw new ServiceException("解除绑定失败，主代理只能一个");
		if ("admin".equals(masterUser))
			throw new ServiceException("主代理用户名不能为admin");
		List<IfwAgentRegInfo> agentRegInfoL = agentRegInfoDao.findByProperties(
				new String[] { "agentName" }, new Object[] { masterUser });
		if (null == agentRegInfoL || agentRegInfoL.isEmpty())
			throw new ServiceException("解除绑定失败，主代理不存在");
		UserBind userBind = userBindDao.findById(masterUser);
		if (null == userBind)
			throw new ServiceException("解除绑定失败，主代理下未绑定任何从代理");
		String su_old = userBind.getSlaveUser();
		// 验证从代理
		String slaveUser = model.getSlaveUser();
		if (StringUtils.isEmpty(slaveUser))
			throw new ServiceException("从代理用户名不能为空");
		slaveUser = slaveUser.replaceAll(" ", "");
		slaveUser = slaveUser.replaceAll("，", ",");
		String[] us = slaveUser.split(",");
		if (slaveUser.startsWith(",") || slaveUser.endsWith(","))
			throw new ServiceException("从代理用户名格式错误");
		String errors = "";
		List<String> userL = new ArrayList<String>();
		List<String> suL = new ArrayList<String>();
		String[] sus = su_old.split(",");
		for (String su : sus)
			suL.add(su);
		for (String u : us) {
			if ("admin".equals(u))
				throw new ServiceException("从代理用户名不能包含admin");
			// 验证从代理用户名和主代理用户名是否相同
			if (u.equals(masterUser))
				throw new ServiceException("从代理用户名不能包含主代理用户名");
			// 验证从代理用户名是否重复
			if (userL.contains(u))
				throw new ServiceException("从代理用户名“" + u + "”重复");
			userL.add(u);
			// 验证代理商是否存在
			agentRegInfoL = agentRegInfoDao.findByProperties(
					new String[] { "agentName" }, new Object[] { u });
			if (null == agentRegInfoL || agentRegInfoL.isEmpty()) {
				errors += "从代理“" + u + "”不存在\n";
				continue;
			}
			if (!suL.contains(u)) {
				errors += "从代理“" + u + "”没有绑定到主代理“" + masterUser + "”下\n";
			}
			// 从旧从代理列表中删除当前从代理
			suL.remove(u);
		}
		if (!StringUtils.isEmpty(errors))
			throw new ServiceException(errors);
		// 取消绑定
		String su_new = "";
		for (String u : suL)
			su_new += "," + u;
		if (StringUtils.isEmpty(su_new)) {
			userBindDao.delete(userBind);
		} else {
			userBind.setSlaveUser(su_new.substring(1));
			String note = model.getNote();
			if (!StringUtils.isEmpty(note))
				userBind.setNote(note);
			userBindDao.update(userBind);
		}
		return "1";
	}
	
	private List<String> getMySlaveUser(String userName) throws Exception {
		List<String> list = new ArrayList<String>();
		UserBind userBind = userBindDao.findById(userName);
		if (null != userBind) {
			String slaveUser = userBind.getSlaveUser();
			if (!StringUtils.isEmpty(slaveUser)) {
				String[] su = slaveUser.split(",");
				for (String s : su) {
					list.add(s);
					list.addAll(getMySlaveUser(s));
				}
			}
		}
		return list;
	}

	/**
	 * 获取当前登录代理商下的所有代理商（累积充值点数、本月新增点数、剩余点数）
	 */
	public String getMyBindUser(int page, int rows) throws Exception {
		String userName = MySecurityContextHandle.getUserName();
		if (StringUtils.isEmpty(userName))
			throw new ServiceException("请先登录");
		List<String> agentNameL = new ArrayList<String>();
		List<IfwAgentRegInfo> agentRegInfoL = null;
		if ("admin".equals(userName)) {
			// 获取所有代理商
			agentRegInfoL = agentRegInfoDao.findAll(null);
		} else {
			// 获取其下代理商
			agentNameL = getMySlaveUser(userName);
		}
		int total;
		if (null == agentRegInfoL) {
			total = agentNameL.size();
		} else {
			total = agentRegInfoL.size();
		}
		JSONObject jo = new JSONObject();
		jo.put("total", total);
		int start = (page - 1) * rows;
		if (start < 0)
			start = 0;
		JSONArray ja = new JSONArray();
		JSONObject jobj;
		String month = myDateHandle.getCurrentDateString().substring(0, 6);
		// 所有用户的累积充值点数
		String sql = "select agent_index, sum(point) from ifw_agent_consume_record where result = 1 and type = 3 group by agent_index;";
		List<Object[]> osL = userBindDao.findByNativeSqlWithStr(sql, null);
		Map<Integer, Integer> map_total = new HashMap<Integer, Integer>();
		for (Object[] os : osL) {
			if (null != os[1])
				map_total.put(Integer.parseInt(os[0].toString()), Integer
						.parseInt(os[1].toString()));
		}
		// 所有用户的当月充值点数
		sql = "select agent_index, sum(point) from ifw_agent_consume_record where result = 1 and type = 3 and ctime like '"
				+ month + "%' group by agent_index;";
		osL = userBindDao.findByNativeSqlWithStr(sql, null);
		Map<Integer, Integer> map = new HashMap<Integer, Integer>();
		for (Object[] os : osL) {
			if (null != os[1])
				map.put(Integer.parseInt(os[0].toString()), Integer
						.parseInt(os[1].toString()));
		}
		for (int i = start; i < start + rows && i < total; i++) {
			IfwAgentRegInfo agent = null;
			if (null == agentRegInfoL) {
				String agentName = agentNameL.get(i);
				// 查询代理商
				List<IfwAgentRegInfo> agentL = agentRegInfoDao
						.findByProperties(new String[] { "agentName" },
								new Object[] { agentName });
				if (null != agentL && !agentL.isEmpty()) {
					agent = agentL.get(0);
				}
			} else {
				agent = agentRegInfoL.get(i);
			}
			if (null == agent)
				continue;
			jobj = new JSONObject();
			jobj.put("agentIndex", agent.getAgentIndex());
			jobj.put("agentName", agent.getAgentName());
			Integer point = agent.getAgentPoint();
			jobj.put("agentPoint", point);
			// 查询代理商点数统计
			// 累计
			Integer agentIndex = agent.getAgentIndex();
			Integer p_total = map_total.get(agentIndex);
			if (null == p_total)
				p_total = 0;
			jobj.put("pointTotal", p_total);
			// 当月
			Integer p = map.get(agentIndex);
			if (null == p)
				p = 0;
			jobj.put("pointTotalMonth", p);
			ja.add(jobj);
		}
		jo.put("rows", ja);
		return jo.toString();
	}
}
